package com.hrzyit.whistle.cases.ui.fragment

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hrzyit.base.common.BaseConstant
import com.hrzyit.base.ext.onClick
import com.hrzyit.base.ui.fragment.BaseMvpFragment
import com.hrzyit.base.utils.AppPrefsUtils
import com.hrzyit.whistle.cases.R
import com.hrzyit.whistle.cases.common.CaseConstant
import com.hrzyit.whistle.cases.data.bean.CaseIndexUserInfoVo
import com.hrzyit.whistle.cases.data.bean.TransferCaseToDeptVo
import com.hrzyit.whistle.cases.injection.component.DaggerCaseCenterComponent
import com.hrzyit.whistle.cases.injection.module.CaseCenterModule
import com.hrzyit.whistle.cases.presenter.TransferSelectUserPresenter
import com.hrzyit.whistle.cases.presenter.view.TransferSelectUserView
import com.hrzyit.whistle.cases.ui.activity.SummaryCaseActivity
import com.hrzyit.whistle.cases.ui.adapter.IndexUserSelectAdapter
import com.hrzyit.whistle.cases.widgets.CaseTransferConfirmPopup
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.fragment_select_user_transfer.*
import me.yokeyword.indexablerv.IndexableLayout
import org.jetbrains.anko.support.v4.intentFor
import org.jetbrains.anko.support.v4.toast

/**
 * 案件管理-批转人员选择界面 Fragment
 * @author YangWei
 * @date 2019/4/19
 */
class IndexUserTransferFragment : BaseMvpFragment<TransferSelectUserPresenter>(), TransferSelectUserView {

    private lateinit var activity: Activity

    // 批转案件id
    private var caseId: Long? = null
    // 当前操作人id
    private var userId: Long? = null
    // 当前选择的单位id
    private var toDeptId: Long? = null
    // 当前选择的单位名称(简称)
    private var deptName: String? = null

    private lateinit var indexAdapter: IndexUserSelectAdapter

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        activity = context as Activity

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.fragment_select_user_transfer, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initAdapter()

        initData()

    }


    /**
     * 初始化联系人 IndexableLayout
     */
    private fun initAdapter() {
        // 初始化联系人索引选择器
        // 适配器
        val indexLayout = mSelectUserTransferIndexLayout as IndexableLayout
        indexLayout.setLayoutManager(LinearLayoutManager(activity))

        // setAdapter
        indexAdapter = IndexUserSelectAdapter(activity)
        indexLayout.setAdapter(indexAdapter)

        // set Material Design OverlayView
        indexLayout.setOverlayStyle_MaterialDesign(Color.BLUE)

        // 全字母排序。  排序规则设置为：每个字母都会进行比较排序；速度较慢
        indexLayout.setCompareMode(IndexableLayout.MODE_FAST)

        // 注册人员选项栏目点击事件
        indexAdapter.setOnItemContentClickListener { _, _, _, entity ->
            // 弹出批转窗口 CaseTransferConfirmPopup
            // 取消其它人员列表选中状态
            indexAdapter.items.forEach {
                if (entity.id == it.id) {
                    // 反选选择
                    it.isChecked = !entity.isChecked
                } else {
                    // 取消其他项选择
                    it.isChecked = false
                }
            }
            indexAdapter.notifyDataSetChanged()
        }

        // 注册批转按钮点击事件
        mSelectUserTransferHeaderBar.getRightView().onClick {
            // 获取单位id、单位名称
            // 获取案件批转响应人id、name
            val checkedEntityList = indexAdapter.items.filter {
                it.isChecked
            }
            checkedEntityList.let {
                val checkedEntity = checkedEntityList[0]
                val transferCaseToDeptVo = TransferCaseToDeptVo()
                // 批转的案件
                transferCaseToDeptVo.caseId = this.caseId!!
                // 批转到单位
                transferCaseToDeptVo.toDeptId = this.toDeptId!!
                transferCaseToDeptVo.deptName = this.deptName!!
                // 批转到人员
                transferCaseToDeptVo.userName = checkedEntity.name
                transferCaseToDeptVo.toUserId = checkedEntity.id
                // 当前操作人
                transferCaseToDeptVo.userId = this.userId!!

                val transferConfirmPopup = CaseTransferConfirmPopup(activity, mPresenter)

                transferConfirmPopup.transferCaseToDeptVo = transferCaseToDeptVo

                XPopup.Builder(activity)
                    .asCustom(transferConfirmPopup)
                    .show()
            }
        }

        // 重写 mSelectUserTransferHeaderBar 的 back 按钮事件,返回上一页
        mSelectUserTransferHeaderBar.getLeftView().onClick{
            fragmentManager!!.popBackStack()
        }

    }


    /**
     * 加载数据
     */
    private fun initData() {

        // 批转到单位id
        toDeptId = arguments?.getLong("toDeptId") // activity.intent.getLongExtra("toDeptId", 0L)

        // 批转到单位名称
        deptName = arguments?.getString("toDeptName")  // activity.intent.getStringExtra("toDeptName")

        // 当前操作人id
        userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)

        // 案件id
        caseId = arguments?.getLong("caseId") // activity.intent.getLongExtra("caseId", 0L)

        mPresenter.selectCaseTransferUserList(0L, userId!!, toDeptId!!)
    }


    /**
     * Dagger2 注入
     */
    override fun injectComponent() {
        DaggerCaseCenterComponent.builder()
            .activityComponent(mActivityComponent)
            .caseCenterModule(CaseCenterModule())
            .build()
            .inject(this)
        mPresenter.mView = this
    }

    /**
     * 获取单位人员列表信息回调
     */
    override fun onGetSelectCaseTransferUserListSuccess(result: MutableList<CaseIndexUserInfoVo>) {
        indexAdapter.setDatas(result)
    }

    /**
     * 保存批示信息成功回调
     */
    override fun onSaveTransferCaseToDeptSuccess(result: Boolean) {
        when (result) {
            true -> {
                toast("保存成功")
                // 结束当前 Fragment
                // 结束上一个 Fragment，即批转单位选择界面
//                fragmentManager!!.popBackStack(
//                    CaseConstant.TAG_FRAGMENT_DEPT_INDEX_FOR_TRANSFER,
//                    FragmentManager.POP_BACK_STACK_INCLUSIVE
//                )
//                fragmentManager!!.popBackStack()
                startActivity(
                    intentFor<SummaryCaseActivity>(
                    ).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                )
            }
            else -> {
                toast("保存失败")
            }
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        Log.e("IndexUserTransferFr","onDestroy.....")
    }

    override fun onPause() {
        super.onPause()
        Log.e("IndexUserTransferFr","onPause.....")
    }
}